package com.kevin.springboot.demos.utils;

import freemarker.cache.FileTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;

/**
 * 大哥写点注释吧！
 * @author: wangyong
 * @date: 2019/8/17 15:44
 */
public class FreemarkerUtil {

	public static String render(Map<String,Object> data,String templateName) throws IOException, TemplateException {
		Writer out = new StringWriter();
		Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
		try {
			configuration.setDefaultEncoding("UTF-8");
			configuration.setDirectoryForTemplateLoading(new ClassPathResource("/templates/").getFile());
			Template template = configuration.getTemplate(templateName);
			template.setEncoding("UTF-8");
			template.process(data,out);
			out.flush();
			return out.toString();
		}finally {
			out.close();
		}
	}
}
